package cn.pet_know.service.impl;

import cn.pet_know.common.constants.DelFlag;
import cn.pet_know.common.my_exception.CustomException;
import cn.pet_know.common.utils.ConverterUtils;
import cn.pet_know.common.utils.GenIdUtil;
import cn.pet_know.dao.mapper.KnowledgeTypeMapper;
import cn.pet_know.entity.KnowledgeType;
import cn.pet_know.entity.dto.KnowledgeTypeDTO;
import cn.pet_know.entity.vo.KnowledgeTypeVO;
import cn.pet_know.service.KnowledgeTypeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class KnowledgeTypeServiceImpl extends ServiceImpl<KnowledgeTypeMapper, KnowledgeType> implements KnowledgeTypeService {

    @Override
    public Boolean addType(KnowledgeTypeDTO knowledgeTypeDTO) {
        // 参数校验
        {
            if (Objects.isNull(knowledgeTypeDTO.getTypeTitle())) {
                throw new CustomException("typeTile is null");
            }
            if (Objects.isNull(knowledgeTypeDTO.getTypeDescription()) || knowledgeTypeDTO.getTypeDescription().length() > 200) {
                throw new CustomException("typeDescription is null or length > 200");
            }
            // 排重
            List<KnowledgeType> list = this.list(
                    new LambdaQueryWrapper<KnowledgeType>()
                            .eq(KnowledgeType::getTypeTitle, knowledgeTypeDTO.getTypeTitle())
                            .eq(KnowledgeType::getDeleted, DelFlag.EXISTS)
            );
            if (!list.isEmpty()) {
                throw new CustomException("The title content is duplicated");
            }
        }
        long uid = GenIdUtil.generatorId();
        knowledgeTypeDTO.setTypeId(uid);
        return this.save(ConverterUtils.copyR(knowledgeTypeDTO,new KnowledgeType()));
    }

    @Override
    public List<KnowledgeTypeVO> listType(KnowledgeTypeDTO knowledgeTypeDTO) {
        List<KnowledgeType> list = this.list(
                new LambdaQueryWrapper<KnowledgeType>()
                        .setEntity(ConverterUtils.copyR(knowledgeTypeDTO, new KnowledgeType()))
                        .eq(KnowledgeType::getDeleted,DelFlag.EXISTS)
        );
        return ConverterUtils.listCopyR(list,KnowledgeTypeVO.class);
    }

    @Override
    public Boolean delType(KnowledgeTypeDTO knowledgeTypeDTO) {
        return this.update(
                new LambdaUpdateWrapper<KnowledgeType>()
                        .setEntity(ConverterUtils.copyR(knowledgeTypeDTO,new KnowledgeType()))
                        .set(KnowledgeType::getDeleted, DelFlag.DELETED)
        );
    }
}